package com.mock.hm.demos.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mock.hm.demos.modal.MultiTrackingReqItem;
import com.mock.hm.demos.modal.MultiTrackingRespItem;
import com.mock.hm.demos.modal.TrackingInfo;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static com.mock.hm.demos.web.JsonConstants.*;

@RestController
@RequestMapping
public class MockRestController {

    private final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

    private String getJson(String invoiceNo) {
        Integer count = map.getOrDefault(invoiceNo, 0);
        if (count == 0) {
            map.put(invoiceNo, 1);
            return JsonConstants.json0;
        } else if (count == 1) {
            map.put(invoiceNo, 2);
            return JsonConstants.json1;
        } else {
            map.put(invoiceNo, 3);
            return JsonConstants.json2;
        }
    }

    @PostMapping("/api/multi_tracking.asp")
    public List<MultiTrackingRespItem> multiTracking(@RequestBody List<MultiTrackingReqItem> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream().map(MultiTrackingReqItem::getInvoice_no).map(no -> {
            MultiTrackingRespItem item = new MultiTrackingRespItem();
            item.setInvoice_no(no);
            item.setRe_invoice_no("R-" + no);
            item.setOrder_no("O-" + no);
            item.setLength("10");
            item.setHeight("10");
            item.setWidth("10");
            List<TrackingInfo> trackingInfos = new ArrayList<>();

            TrackingInfo tracking1 = new TrackingInfo();
            tracking1.setJngdat("20230126");
            tracking1.setJngtim("0656");
            tracking1.setJngnum("17");
            tracking1.setJngcde("간선하차");
            tracking1.setPostte("");
            tracking1.setPostnm("중앙일보");

            TrackingInfo tracking2 = new TrackingInfo();
            tracking2.setJngdat("20230127");
            tracking2.setJngtim("0043");
            tracking2.setJngnum("18");
            tracking2.setJngcde("배달준비");
            tracking2.setPostte("");
            tracking2.setPostnm("중앙일보(장세규)");

            TrackingInfo tracking3 = new TrackingInfo();
            tracking3.setJngdat("20230127");
            tracking3.setJngtim("0618");
            tracking3.setJngnum("19");
            tracking3.setJngcde("배달완료");
            tracking3.setPostte("");
            tracking3.setPostnm("중앙일보(장세규)");

            // 将所有TrackingInfo对象加入list
            trackingInfos.add(tracking1);
            trackingInfos.add(tracking2);
            trackingInfos.add(tracking3);

            // 设置trackingInfo列表到响应项
            item.setTracking_info(trackingInfos);

            return item;
        }).collect(Collectors.toList());
    }


    @GetMapping("/api/tracking.asp")
    public JSONObject tracking(@RequestParam("invoice_no") String invoiceNo, @RequestParam(value = "type", required = false) Integer type) {
        String json = JsonConstants.json2;


        JSONObject jsonObject = JSONObject.parseObject(json);
        // 将 jsonObject中的invoice_no全部替换为输入的invoiceNo,re_invoice_no全部替换为invoiceNo+"R-"
        JSONArray array = jsonObject.getJSONArray("tracking_info");
        for (Object object : array) {

            if (object instanceof JSONObject) {
                JSONObject jsonObject1 = (JSONObject) object;
                jsonObject1.put("invoice_no", invoiceNo);
                jsonObject1.put("re_invoice_no", "R" + invoiceNo);
            }
        }
        return jsonObject;
    }

    @PostMapping("/gt/**")
    public JSONObject getGtRes() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "SUCCESS");
        return jsonObject;
    }

    @PostMapping("/api/orderH.asp")
    public JSONObject orderH(@RequestBody JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        result.put("success", "true");
        // 年月日+随机4位数字字符串
        Random random = new Random();
        String randomNo = String.format("%04d", random.nextInt(10000));
        String no = new SimpleDateFormat("yyyyMMdd").format(new Date()) + randomNo;
        result.put("re_invoice_no", no);

        return result;
    }

    @PostMapping("/wspsc/apiRestLogisticaInversa/json/grabar")
    public JSONObject grabar(@RequestBody JSONObject input) {
        JSONObject result = new JSONObject();
//        {"codigoRetorno":0,"mensajeRetorno":null}
        result.put("codigoRetorno", 0);
        result.put("mensajeRetorno", null);
        return result;
    }

    @PostMapping("/wspsc/apiRestSeguimientoEnviosk8s/json/seguimientoEnvio")
    public JSONObject seguimientoEnvio(@RequestBody JSONObject inpit) {
        long number1 = System.currentTimeMillis();
        long number2 = number1 + (long) (Math.random() * 10000);
        String codUnico1 = "3583000" + number1;
        String codUnico2 = "3583000" + number2;
        String string = String.format(CEX_TRACK, codUnico1, codUnico2);
        return JSONObject.parseObject(string);
    }

    @PostMapping("/shipment2/usps")
    public JSONObject uspsCreateLabel(@RequestBody JSONObject input) {
//        LUPS-1938603220901433344-1751034002144
        String requestId = input.getString("requestId");
        String orderId = "LUPS-" + requestId + "-" + System.currentTimeMillis();
        return JSONObject.parseObject(String.format(USPS_CREATE, requestId, orderId));
    }

    @GetMapping("/shipment2/label/{orderId}")
    public JSONArray uspsGetLabel(@PathVariable String orderId) {
        String trackingNo = "T" + System.currentTimeMillis();
        return JSONArray.parseArray(String.format(USPS_GET_SUCCESS, orderId, trackingNo, trackingNo, trackingNo));
    }

    @GetMapping("/shipment2/usps/tracking/{trackingNo}")
    public JSONArray uspsTracking(@PathVariable String trackingNo) {
        return JSONArray.parseArray(String.format(USPS_TRACKING2, trackingNo));
    }

}
